<?php

class FeedController extends Zend_Controller_Action 
{
	
    /**
     * @var Zend_Translate
     */
    private $_translate;
    
	public function init() 
	{
		$this->_translate = Zend_Registry::get('Zend_Translate');
	}
	
	/**
	 * Try to get feed information and populate the add form
	 * Also check for validity of inserted url
	 * - Ajax action
	 * 
	 * @return void
	 */
	public function getfeedinfoAction()
	{
		$this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $feedurl = $this->getRequest()->getParam('feedurl');
        
        if (empty($feedurl)) {
        	$message = $this->_translate->translate('emptyurl');
            $return = Zend_Json::encode(array('isValid' => false,
                                              'message' => $message
                                             ));
        } else {
        	try {
        		$feed = FireFeed_Feed_Consumer::getFeedInfo($feedurl);
        		$channel = array_merge($feed->getOptions(), 
        		                       array('isValid' => true));
                $return = Zend_Json::encode($channel);
        	} catch (Exception $e) {
        		$message = $this->_translate->translate('URLerror');
        		$message = $e->getMessage();
                $return = Zend_Json::encode(
                    array('isValid' => false, 'message' => $message)
                );
          	}
        }
        $this->_response->appendBody($return);
        return;
	}
	
	/**
     * Form usato dall'amministratore per aggiungere Feed Box nella index di 
     * FireFeed
     * 
     * @return void
     */
    public function activeaddfeedAction()
    {
        $this->_helper->layout->disableLayout();
        
        $this->view->formAddfeed = new Form_Feed();
    }
    
    /**
     * Aggiunge un feed nel sistema
     * - Ajax action
     *  
     * @return void
     */
    public function addfeedAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $request = $this->getRequest();

        if ($request->isPost()) {
            $post = $request->getPost();
            $form = new Form_Feed();
            
            if ($form->isValid($post)) {
                $resultArray = array('error' => false);
                $factory = Model_Factory::getInstance();
                $service = $factory->getFeedService();
                $newsService = $factory->getNewsService();
                
                $user = Zend_Auth::getInstance()->getIdentity();
                
                $category = new Model_Entity_Category();
                $category->setOid($form->getValue('category'));
                
                $feed = new Model_Entity_Feed($form->getValues());
                $feed->setCreatedBy($user);
                $feed->setCategory($category);
               
                $service->addFeed($feed);
                
                $news = FireFeed_Feed_Consumer::consumeFeed($feed, true);
                foreach($news as $entry) {
                    $newsService->addNews($entry);
                }
            } else {
                $messages = FireFeed_Form_MyMessages::getMessages($form);
                
                $messages = array('messages' => $messages);
                $resultArray = array('error' => true); 
                $resultArray = array_merge($resultArray, $messages);
            }
            
            $return = Zend_Json::encode($resultArray);
            $this->_response->appendBody($return);
        } else {
            $this->_forward('activeaddfeed');
        }
    }
    
    /**
     * Form usato dall'utente per aggiungere Feed 
     * 
     * @return void
     */
    public function activeadduserfeedAction()
    {
        $this->_helper->layout->disableLayout();

        $factory = Model_Factory::getInstance();
        $service = $factory->getCategoryService();
        $userID = Zend_Auth::getInstance()->getIdentity()->oid;
        
        $categories = $service->getUserCategories($userID);
        
        $resultArray = array();
        foreach ($categories as $category) {
            $resultArray += array($category->oid => $category->name);
        }
        
        $form = new Form_Feed();
        
        $form->getElement('category')->setMultiOptions($resultArray);
        $this->view->formAddfeed = $form;
    }
    
    /**
     * Aggiunge un feed utente nel sistema
     * - Ajax action
     *  
     * @return void
     */
    public function adduserfeedAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $request = $this->getRequest();

        if ($request->isPost()) {
            $post = $request->getPost();
            
            if($this->_getParam('param',0) == 1) {
            	$form = new Form_AddUserFeed();
            } else {
                $form = new Form_Feed();
            }
            
            if ($form->isValid($post)) {
                $resultArray = array('error' => false);
                $factory = Model_Factory::getInstance();
                $service = $factory->getFeedService();
                $newsService = $factory->getNewsService();
                $user = Zend_Auth::getInstance()->getIdentity();
                
                $category = new Model_Entity_Category();
                $category->setOid($form->getValue('category'));
                
                $feed = new Model_Entity_Feed($form->getValues());
                $feed->setCreatedBy($user);
                $feed->setCategory($category);
               
                $service->addUserFeed($feed);
                
                $news = FireFeed_Feed_Consumer::consumeFeed($feed);
                //foreach($news as $entry) {
                //    $newsService->addNews($entry);
                foreach($news as $item) {
	                $item->setOwners($user);
	                
	                $id = $newsService->addNews($item);
	                
	                $item->setOid($id);
	                $newsService->addUserNews($item);
	            }
            } else {
                $messages = FireFeed_Form_MyMessages::getMessages($form);
                
                $messages = array('messages' => $messages);
                $resultArray = array('error' => true); 
                $resultArray = array_merge($resultArray, $messages);
            }
            
            $return = Zend_Json::encode($resultArray);
            $this->_response->appendBody($return);
        } else {
            $this->_forward('activeaddfeed');
        }
    }
    
    /**
     * Reatrieve all feed in specified category and return in Json format
     * - Ajax action
     * 
     * @return void
     */
    public function loadfeedsbycategoryAction()
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();

        $factory = Model_Factory::getInstance();
        $service = $factory->getFeedService();
        
        $criteria = array();
        $criteria['catID'] = $this->getRequest()->getPost('catID'); 
                
        $feeds = $service->searchFeeds($criteria)->getItems(null, null);
        
        $resultArray = array();
        foreach ($feeds as $feed) {
            $result = $feed->getOptions();
            
            unset($result['description']);
            unset($result['news']);
            
            $resultArray[] = $result;
        }
        
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
    /**
     * Loads the history feeds page
     * - Ajax action
     * 
     * @return void
     */
    public function loadfeedshistoryAction()
    {
    	$this->_helper->layout->disableLayout();
    	
    	$factory = Model_Factory::getInstance();
        $service = $factory->getCategoryService();
        $categories = $service->getCategories();
        
        $resultArray = array('' => '');
        foreach ($categories as $category) {
            $resultArray += array($category->oid => $category->name);
        }
        
        $userID = Zend_Auth::getInstance()->getIdentity()->oid;
        $arrayVal = array(''=>'allfeeds', $userID=>'minefeeds');
        
        $form = new Form_FeedHistory();
        $form->getElement('category')->setMultiOptions($resultArray);
    	$form->getElement('owner')->setMultiOptions($arrayVal);
        $this->view->feedHistoryForm = $form;
    }
    
    /**
     * Reatrieve all feed and render them in a list
     * - Ajax action
     * 
     * @return void
     */
    public function loadfeedslistAction()
    {
    	$this->_helper->layout->disableLayout();
    	
    	$searchSession = new Zend_Session_Namespace('searchfeeds');
        
    	$request = $this->getRequest();
        
    	if ($request->isPost()) {
            $form = new Form_FeedHistory();
            $post = $request->getPost();

            if ($form->isValid($post)) {
                $values = $form->getValues();
                
		        $factory = Model_Factory::getInstance();
		        $service = $factory->getFeedService();
		        
                if (0 == $this->_getParam('page', 0)) {
                    $searchSession->unsetAll();
                    $searchSession->owner = $form->getValue('owner');
                    $searchSession->category = $form->getValue('category');
                    $searchSession->contains = $form->getValue('contains');
                }
                
		        $criteria = array();
		        $criteria['catID'] = $searchSession->category;
		        $criteria['owner'] = $searchSession->owner;
		        $criteria['contains'] = $searchSession->contains;
		        
		        $feeds = new Zend_Paginator($service->searchFeeds($criteria));
                $feeds->setCurrentPageNumber($this->_getParam('page', 1));
                $feeds->setItemCountPerPage(5);
                $feeds->setPageRange(5);
                
		        $this->view->feeds = $feeds;
            } else {
            	$this->getResponse()->appendBody("invalidparam");
            }
    	}
    }	
    
    /**
     * Delete a Feed
     * - Ajax action
     * 
     * @return void
     */
    function deletefeedAction() 
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $resultArray = array('error' => false);
        
        $feedID = $this->_getParam('elementID');
        
        if (!empty($feedID) && is_numeric($feedID) && ($feedID > 0)) {
            $factory = Model_Factory::getInstance();
            $service = $factory->getFeedService();
            
            try {
                $service->deleteFeed($feedID);
            } catch (Model_ZendDb_CantDeleteException $e) {
                $message = $this->_translate->translate('cantdelete');
                $resultArray = array('error' => true,
                                     'message' => $message);
            }
        } else {
            $message = $this->_translate->translate('invalidparam');
            $resultArray = array('error' => true,
                                 'message' => $message);
        }
                   
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
    /**
     * Delete a Feed
     * - Ajax action
     * 
     * @return void
     */
    function deleteuserfeedAction() 
    {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        
        $resultArray = array('error' => false);
        
        $feedID = $this->_getParam('elementID');
        
        if (!empty($feedID) && is_numeric($feedID) && ($feedID > 0)) {
            $factory = Model_Factory::getInstance();
            $service = $factory->getFeedService();
            
            $feed = new Model_Entity_Feed();
            $feed->setOid($feedID);
            $feed->setOwners(Zend_Auth::getInstance()->getIdentity());
            
            try {
                $service->deleteUserFeed($feed);
            } catch (Model_ZendDb_CantDeleteException $e) {
                $message = $this->_translate->translate('cantdelete');
                $resultArray = array('error' => true,
                                     'message' => $message);
            }
        } else {
            $message = $this->_translate->translate('invalidparam');
            $resultArray = array('error' => true,
                                 'message' => $message);
        }
                   
        $return = Zend_Json::encode($resultArray);
        $this->_response->appendBody($return);
    }
    
    /**
     * Form usato dall'utente per aggiungere Feed tra quelli suggeriti 
     * o top ten
     * 
     * @return void
     */
    public function activeadduserfeedtopsuggestAction()
    {
    	$this->_helper->layout->disableLayout();

    	$feedURL = $this->_getParam('feedURL',0);
    	
    	if (!empty($feedURL) && ($feedURL !== 0)) {
    	
	        $factory = Model_Factory::getInstance();
	        $service = $factory->getCategoryService();
	        $userID = Zend_Auth::getInstance()->getIdentity()->oid;
	        
	        $categories = $service->getUserCategories($userID);
	        
	        $resultArray = array();
	        foreach ($categories as $category) {
	            $resultArray += array($category->oid => $category->name);
	        }
	        
	        $form = new Form_AddUserFeed();
	        $form->getElement('url')->setValue($feedURL);
	        
	        $form->getElement('category')->setMultiOptions($resultArray);
	        $this->view->formAddfeed = $form;
	        
    	} else {
    	   $this->_helper->viewRenderer->setNoRender();
    	   $message = $this->_translate->translate('invalidparam');
    	   $this->_response->appendBody($message);
    	}
    }
    
    
}
